﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YCMS.Domain.Abstract;
using YCMS.Domain.Concrete;
using YCMS.Domain.Entities;
using YCMS.Models;
using PagedList;

namespace YCMS.WebUI.Controllers
{
    public class DockController : Controller
    {
        private IDockRepository dockRepository;
        private IMemberRepository memberRepository;

        public DockController(IDockRepository repository, IMemberRepository memberRepository)
        {
            EfDbContext context = new EfDbContext();
            this.dockRepository = repository;
            this.dockRepository.Context = context;
            this.memberRepository = memberRepository;
            this.memberRepository.Context = context;
        }

        //
        // GET: /Dock/

        public ViewResult List(string sortOrder, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.DockNameSortOrder = String.IsNullOrEmpty(sortOrder) ? "DockName desc" : "";
            ViewBag.DockAreaSortOrder = sortOrder == "DockArea" ? "DockArea desc" : "DockArea";
            ViewBag.VacantSortOrder = sortOrder == "Vacant" ? "Vacant desc" : "Vacant";
            ViewBag.PageNumber = page;
 
            DockListViewModel dockListViewModel = new DockListViewModel();
            switch (sortOrder)
            {
                case "DockName desc":
                    dockListViewModel.docks = dockRepository.Docks.OrderByDescending(d => d.DockName);
                    break;
                case "DockArea":
                    dockListViewModel.docks = dockRepository.Docks.OrderBy(d => d.DockArea);
                    break;
                case "DockArea desc":
                    dockListViewModel.docks = dockRepository.Docks.OrderByDescending(d => d.DockArea);
                    break;
                case "Vacant":
                    dockListViewModel.docks = dockRepository.Docks.OrderBy(d => d.Vacant);
                    break;
                case "Vacant desc":
                    dockListViewModel.docks = dockRepository.Docks.OrderByDescending(d => d.Vacant);
                    break;
                default:
                    dockListViewModel.docks = dockRepository.Docks.OrderBy(d => d.DockName);
                    break;


            }
            int pageSize = 10;
            int pageIndex = (page ?? 1) - 1;
            dockListViewModel.docks = dockListViewModel.docks.ToPagedList(pageIndex, pageSize);
            dockListViewModel.pageNumber = page;
            dockListViewModel.sortOrder = sortOrder;
            return View(dockListViewModel);
        }

        public ActionResult Details(int id, string sortOrder, int? pageNumber)
        {
            Dock dock = dockRepository.GetDockById(id);
            SelectList list = PopulateMemberDocks(dock);
            DockListViewModel viewModel = new DockListViewModel();
            viewModel.dock = dock;
            viewModel.pageNumber = pageNumber;
            viewModel.sortOrder = sortOrder;
            viewModel.MemberDocks = list;
            return View(viewModel);
        }

        private SelectList PopulateMemberDocks(Dock dock)
        {
            var memberDockQuery = from m in dock.Members
                                  select m.LastName;
            SelectList list = new SelectList(memberDockQuery);
            return list;
        }
        public ActionResult Edit(int id, string sortOrder, int? pageNumber)
        {
            Dock dock = dockRepository.GetDockById(id);

            DockListViewModel viewModel = new DockListViewModel();
            var selectedMember = from m in dock.Members
                                 select m.ID;
            List<int> list = selectedMember.ToList();

            viewModel.AllMembers = PopulateMemberDropDownList(list);
            viewModel.dock = dock;
            viewModel.pageNumber = pageNumber;
            viewModel.sortOrder = sortOrder;
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Edit(DockListViewModel model)
        {
            Dock dock = model.dock;
            try
            {
                if (ModelState.IsValid)
                {
                    Dock dockToUpdate = dockRepository.GetDockById(dock.ID);
                    dockToUpdate.DockArea = dock.DockArea;
                    dockToUpdate.DockName = dock.DockName;
                    dockToUpdate.MaxBeam = dock.MaxBeam;
                    dockToUpdate.MaxLength = dock.MaxLength;
                    dockToUpdate.Vacant = dock.Vacant;

                    List<Member> membersToRemove = new List<Member>();
                    foreach (var member in dockToUpdate.Members)
                    {
                        membersToRemove.Add(member);
                    }
                    foreach (var member in membersToRemove)
                    {
                        dockToUpdate.Members.Remove(member);
                    }
                    foreach (var memberID in model.SelectedMembers)
                    {
                        Member member = memberRepository.GetMemberByID(memberID);
                        dockToUpdate.Members.Add(member);
                    }
                    dockRepository.UpdateDock(dockToUpdate);
                    dockRepository.Save();
                    return RedirectToAction("List", "Dock", new {sortOrder = model.sortOrder, page = model.pageNumber});
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes.  Try again later");
            }
            return View(dock);

        }
        public ActionResult Create()
        {
            return View();
        }

        public ActionResult Delete(int id, bool? saveChangesError)
        {
            if (saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Unable to save changes.  Try again later";
            }
            Dock dock = dockRepository.GetDockById(id);
            return View(dock);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                Dock dock = dockRepository.GetDockById(id);
                dockRepository.DeleteDock(dock);
                dockRepository.Save();
            }
            catch (DataException)
            {
                return RedirectToAction("Delete",
                    new System.Web.Routing.RouteValueDictionary { { "id", id }, { "saveChangesError", true } }); 
            }

            return RedirectToAction("List", "Dock");
        }

        [HttpPost]
        public ActionResult Create(Dock dock)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    dockRepository.InsertDock(dock);
                    dockRepository.Save();
                    return RedirectToAction("List", "Dock");
                }
            }
            catch(DataException)
            {
                ModelState.AddModelError("", "Unable to save changes.  Try again later");
            }
            return View(dock);
        }

        private MultiSelectList PopulateMemberDropDownList(IEnumerable<int> selectedMembers)
        {

            var memberQuery = from m in memberRepository.Members
                              orderby m.LastName
                              select m;

            MultiSelectList list = new MultiSelectList(memberQuery, "ID", "LastName", selectedMembers);
            return (list);
        }

        private Member GetMemberByID(int id)
        {
            return memberRepository.GetMemberByID(id);
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}
